package com.zjuh.qss.biz.bo.impl;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wint.lang.magic.MagicList;
import wint.lang.utils.CollectionUtil;
import wint.lang.utils.FileUtil;
import wint.lang.utils.MapUtil;
import wint.lang.utils.StringUtil;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.SelectedItem;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.User;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.TaobaokeItemsConvertRequest;
import com.taobao.api.request.TmallSelectedItemsSearchRequest;
import com.taobao.api.request.UsersGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.TaobaokeItemsConvertResponse;
import com.taobao.api.response.TmallSelectedItemsSearchResponse;
import com.taobao.api.response.UsersGetResponse;
import com.zjuh.qss.biz.bo.TaobaoOpenBO;

public class TaobaoOpenBOImpl implements TaobaoOpenBO {

	private static final Logger log = LoggerFactory.getLogger(TaobaoOpenBOImpl.class);
	
	private String url;
	
	private String appkey;
	
	private String secret;
	
	private String nick;
	
	private long searchProductPageSize = 100;	

	private TaobaoClient getTaobaoClient() {
		DefaultTaobaoClient ret = new DefaultTaobaoClient(url, appkey, secret);
		return ret;
	}
	
	public List<Item> searchItems(long cid, long page) throws ApiException { 
		return searchItems(cid, null, page);
	}
	
	public List<Item> searchItems(long cid, String q, long page) throws ApiException {
	/*	TaobaoClient client = getTaobaoClient();
		ItemsSearchRequest req = new ItemsSearchRequest();
		req.setCid(cid);
		req.setPageSize(searchProductPageSize);
		if (!StringUtil.isEmpty(q)) {
			req.setQ(q);
		}
		if (page > 0) {
			req.setPageNo(page);
		}
		req.setFields("num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,volume");
		ItemsSearchResponse response = client.execute(req);
		if (!response.isSuccess()) {
			return CollectionUtil.newArrayList();
		}
		ItemSearch itemSearch = response.getItemSearch();
		if (itemSearch == null) {
			return CollectionUtil.newArrayList();
		}
		return itemSearch.getItems();*/
		return null;
	}
	
	public List<String> searchTmallSelectedItems(long cid) throws ApiException {
		TaobaoClient client= getTaobaoClient();
		TmallSelectedItemsSearchRequest req=new TmallSelectedItemsSearchRequest();
		req.setCid(cid);
		TmallSelectedItemsSearchResponse response = client.execute(req);
		
		if (!response.isSuccess()) {
			log.warn("searchItemsTmall error. " +response.getErrorCode() +":"+ response.getMsg());
			return CollectionUtil.newArrayList();
		}
		
		List<SelectedItem> selectItems = response.getItemList();
		if (CollectionUtil.isEmpty(selectItems)) {
			return CollectionUtil.newArrayList();
		}
		List<String> ret = CollectionUtil.newArrayList();
		for (SelectedItem selectedItem : selectItems) {
			String trackIid = selectedItem.getTrackIid();
			ret.add(trackIid);
		}
		return ret;
	}
	
	
	public List<ItemCat> getItemCatsByParentId(long parentCid) throws ApiException  {
		TaobaoClient client=getTaobaoClient();
		ItemcatsGetRequest req = new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent");
		req.setParentCid(parentCid);
		ItemcatsGetResponse response = client.execute(req);
		if (!response.isSuccess()) {
			return CollectionUtil.newArrayList();
		}
		return response.getItemCats();
	}
	
	public Map<String, User> getUserByNicks(Collection<String> nicks) throws ApiException{
		TaobaoClient client=getTaobaoClient();
		UsersGetRequest req=new UsersGetRequest();
		req.setFields("user_id,nick");
		req.setNicks(CollectionUtil.join(CollectionUtil.newArrayList(nicks), ","));
		UsersGetResponse response = client.execute(req);
		if (!response.isSuccess()) {
			return MapUtil.newHashMap();
		} else {
			List<User> users = response.getUsers();
			Map<String, User> ret = MapUtil.newHashMap();
			for (User user : users) {
				ret.put(user.getNick(), user);
			}
			return ret;
		}
	}
	
	public Item getTaobaoItem(Long itemId) throws ApiException {
		TaobaoClient client=getTaobaoClient();
		ItemGetRequest req=new ItemGetRequest();
		req.setFields("num_iid,title,price,detail_url,nick,pic_url");
		req.setNumIid(itemId);
		ItemGetResponse response = client.execute(req);
		if (!response.isSuccess()) {
			return null;
		}
		return response.getItem();
	}

	@Override
	public List<Item> queryItemDescsByTrackIids(List<String> trackIids) throws ApiException {
		TaobaoClient client=new DefaultTaobaoClient(url, appkey, secret);
		ItemsListGetRequest req=new ItemsListGetRequest();
		req.setFields("num_iid,desc");
		//req.setNumIids("123456,223456");
		req.setTrackIids(CollectionUtil.join(trackIids, ","));
		ItemsListGetResponse response = client.execute(req);
		return response.getItems();
	}

	public TaobaokeItem queryTaobaokeItem(Long itemId) throws ApiException {
		MagicList<Long> itemIds = MagicList.wrap(itemId);
		List<TaobaokeItem> items = queryTaobaokeItems(itemIds);
		if (CollectionUtil.isEmpty(items)) {
			return null;
		}
		return items.get(0);
	}

	@Override
	public List<TaobaokeItem> queryTaobaokeItems(List<Long> itemIds) throws ApiException {
		TaobaoClient client=getTaobaoClient();
		TaobaokeItemsConvertRequest req= new TaobaokeItemsConvertRequest();
		req.setFields("num_iid,nick,title,detail_url,taobaoke_items,commission_rate,price,click_url,pic_url,commission,volume,seller_credit_score");
		req.setNumIids(CollectionUtil.join(itemIds, ","));
		req.setNick(nick);
		TaobaokeItemsConvertResponse response = client.execute(req);
		List<TaobaokeItem> taobaokeItems = response.getTaobaokeItems();
		return taobaokeItems;
	}
	
	public List<TaobaokeItem> queryTaobaokeItemsByTrackIids(List<String> trackIids) throws ApiException {
		TaobaoClient client=getTaobaoClient();
		TaobaokeItemsConvertRequest req= new TaobaokeItemsConvertRequest();
		req.setFields("num_iid,nick,title,detail_url,taobaoke_items,commission_rate,price,click_url,pic_url,commission,volume,seller_credit_score");
		req.setTrackIids(CollectionUtil.join(trackIids, ","));
		req.setNick(nick);
		TaobaokeItemsConvertResponse response = client.execute(req);
		List<TaobaokeItem> taobaokeItems = response.getTaobaokeItems();
		return taobaokeItems;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}

	public void setSecretPath(String secretPath) {
		try {
			this.secret = StringUtil.trimToEmpty(FileUtil.readAsString(new File(secretPath)));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void setNick(String nick) {
		this.nick = nick;
	}


}
